package com.eobard.controller;

import com.eobard.constant.SecKillConstant;
import com.eobard.dto.ProductSeckillDto;
import com.eobard.entity.Product;
import com.eobard.enums.SecKillEnum;
import com.eobard.mq.RabbitService;
import com.eobard.service.ProductService;
import com.eobard.utils.SecKillUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.Executor;

/**
 * @Author: Eobard Gu
 * @Date: 2025-07-16
 * @Description: TODO
 */
@RestController
@RequestMapping("api/v1")
@Slf4j
public class ProductController {
    @Autowired
    private ProductService productService;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private Executor threadPoolExecutor;

    @Autowired
    private SecKillUtils secKillUtils;

    @GetMapping("/getAll")
    public ResponseEntity getAll() {
        List<Product> list = productService.list();
        return new ResponseEntity(list, HttpStatus.OK);
    }

    //适用于并发量不高的秒杀
    @GetMapping("/seckill/{productId}")
    public ResponseEntity seckill(@PathVariable Long productId) {
        String userId = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
        SecKillEnum status = productService.purchase(userId, productId);
        return new ResponseEntity(status.msg, HttpStatus.OK);
    }


    //通过异步消息队列进行秒杀
    @GetMapping("/mq/seckill/{productId}")
    public ResponseEntity seckill2(@PathVariable Long productId) {
        //模拟用户ID
        String userId = UUID.randomUUID().toString().replace("-", "");

        //为当前用户生产秒杀ID
        String secKillId = UUID.randomUUID().toString().replace("-", "");
        secKillUtils.updateSecKillStatus(secKillId, SecKillEnum.WAITING.msg);

        //模拟DTO传递
        ProductSeckillDto seckillDto = new ProductSeckillDto(userId, productId, secKillId);

        //异步发送消息
        threadPoolExecutor.execute(() -> {
            rabbitService.sendMessage(SecKillConstant.SECKILL_EXCHANGE, SecKillConstant.SECKILL_KEY, seckillDto);
        });

        return new ResponseEntity(secKillId, HttpStatus.OK);
    }

    //获取对应的秒杀结果
    @GetMapping("/mq/seckill/result/{secKillId}")
    public ResponseEntity callback(@PathVariable String secKillId) {
        return new ResponseEntity(secKillUtils.getSecKillStatus(secKillId), HttpStatus.OK);
    }


    @GetMapping("test")
    public void test() {
        DateTimeFormatter df=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String time = df.format(LocalDateTime.now());
    }
}
